# WeatherManager - Download local weather condition information from the net.
# Copyright (C) 2007 Lauri Taimila
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"

import os
from pysqlite2 import dbapi2 as sqlite
from backend.components.weather.weather_fetcher import WeatherFetcher

# Messaging system
from backend.core.message import Message
from backend.core.message_type_priority import MessageType
from backend.core.message_bus import MessageBus
from backend.core.message_handler import MessageHandler

class WeatherManager(MessageHandler):
    """
    WeatherManager is a backend component that downloades local weather
    conditions from the internet. Downloaded weather information is stored
    in weather cache (SQLite database). Weather conditions are updated when
    WeatherFetcher receives UPDATE_WEATHER message from the messagebus.
    """

    # Feed cache database file
    WEATHER_DB = os.path.expanduser('~/.entertainer/cache/weather.db')

    def __init__(self, message_bus, logger, configuration):
        """
        Create a new WeatherFetcher object. Only one object should be created.
        @param message_bus: Backend messagebus object
        @param logger: Logger object
        @param configuration: Configuration object
        """
        self.message_bus = message_bus
        self.logger = logger
        self.location_information = ""; #TODO: Set correct value from configuration
        if not os.path.exists(self.WEATHER_DB):
            self.createWeatherCacheDatabase()

    def updateFeedCache(self):
        """
        Update all feeds to cache in a new thread and after 
        that emit FEED_DB_UPDATED message.
        """
        fetch_thread = WeatherFetcher(self.message_bus, 
                                      self.logger,
                                      self.location_infromation)
        fetch_thread.start()
    
    def createWeatherCacheDatabase(self):
        """
        Create a weather cache database file and tables.
        """
        db_conn = sqlite.connect(self.WEATHER_DB)
        db_cursor = db_conn.cursor()
        #TODO: Define table. What information we want to store?
        db_cursor.execute("""CREATE TABLE weather(
                                          temperature TEXT, 
                                          time TIME,
                                          date DATE,
                                          PRIMARY KEY(time,date))""")
        db_conn.commit()
        db_conn.close()
        
    # Implementes MessageHandler interface
    def handleMessage(self, message):
        if message.get_type() == MessageType.UPDATE_WEATHER:
            self.updateWeatherCache()
            
    def getName(self):
        return "WeatherFetcher"
